package tpenchere.controllers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.EventObject;

import javax.swing.ActionMap;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import org.jdesktop.application.Action;
import org.jdesktop.application.Application.ExitListener;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.Task;

import tpenchere.application.MainApplication;
import tpenchere.model.Categorie;
import tpenchere.model.Produit;
import tpenchere.model.User;
import tpenchere.service.EnchereServiceOperations;
import tpenchere.service.MainContext;
import tpenchere.ui.AbstractView;
import tpenchere.ui.contents.BidWindow;

/**
 * 
 */
public class BidController extends DefaultController {

	/** the view is useful to retrieve info (e.g. the selected item) */
	private final BidWindow view;

	public BidController(BidWindow pView) {
		view = pView;
	}
	
	public void loadCategories() {
		EnchereServiceOperations serviceImpl = provider.getService();
		try {
			Categorie[] categories = serviceImpl.getAllRootCategorie();
			view.getProductCategory().removeAllItems();
			for(int i = 0; i < categories.length; i++){				
				view.getProductCategory().addItem(categories[i].nom);
			}
		} catch (Exception e) {
			view.showError("An error has occured");
			e.printStackTrace();
		}
	}
	
	@Action(name = "view.bid.button.cancel")
	public void cancel() {
		this.switchToView(AbstractView.ViewType.HOME);
	}
	
	@Action(name = "view.bid.button.create")
	public void createBid() {
		Produit newProduct = new Produit();
		String catName = view.getProductCategory().getSelectedItem().toString();
		catName = catName != null ? catName : view.getProductCategory().getEditor().getItem().toString();
		catName = catName == null ? "" : catName;
		Categorie cat = new Categorie();
		cat.setNom(catName);
		cat.setCategorieFille(new Categorie[0]);
		
		newProduct.setIdProduit(0);
		newProduct.setLibelle(view.getProductLabel().getText());
		newProduct.setDescriptif(view.getProductDescription().getText());
		newProduct.setPseudoVendeur(session.getLoggedUser().pseudo);
		newProduct.setPrixDepart(Float.parseFloat(view.getProductStartingBid().getText()));
		newProduct.setPrixImmediat(newProduct.prixDepart);
		newProduct.setCategorie(cat);
		
		newProduct.setEcheance(view.getProductDueDate().getDate().getTime());
		
		EnchereServiceOperations serviceImpl = provider.getService();
		try {
			serviceImpl.createProduit(newProduct);
			this.switchToView(AbstractView.ViewType.HOME);
		} catch (Exception e) {
			view.showError("An error has occured");
			e.printStackTrace();
		}		
	}
}
